// pages/buy/buy.js
let app = getApp();
let wcache =require('../../utils/wcache.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupon:null,
    orderBean:null,
    modetype :1 ,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.vcid = options.vcid;
    this.type = options.type;
    this.courseInfoId = options.courseInfoId;

    this.setData({
      modetype:this.type
    });

    app.event.on("coupon", this, (data) => {
      this.setData({ coupon:data})
    })
    this.getBuyDetial();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.event.remove("coupon", this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  getBuyDetial(){
    let obj ={
      courseInfoId: this.type == 1 ? wcache.get("courseInfoId", "") : this.courseInfoId,
      uid: app.globalData.userBean().id,
      type: this.type,
      vcid: this.vcid == undefined ? "" : this.vcid
    }
    app.httpUtils.postLoading(app.Api.GETBUYDETAILS,obj).then(res=>{
          if(res.code == '00'){
            this.setData({
              orderBean:res.data
            })
          }
      })
  },

  payOrder(){
    if (this.data.orderBean ==null){return}
    app.httpUtils.postLoading(app.Api.PAYMENT, {
      uid: app.globalData.userBean().id,
      pid: this.data.orderBean.id,
      cid: this.data.coupon != null ? this.data.coupon.id : ""
    }).then(res => {
      wx.showToast({
        title: res.msg,
      })
      if (res.code == '00') {
        setTimeout(res => { 
          wx.navigateBack({})
          if(this.type==2){
            app.event.emit("buyvideo","")
          }else if(this.type==1){
            app.event.emit("buytiku", "")
          }
        }, 200);
      }else if(res.code="05"){
          wx.navigateTo({
            url: '../recharge/recharge',
          })
      }
    })
  },

  /**
   * 使用有会全
   */
  useCoupon(){
    wx.navigateTo({
      url: '../coupon/coupon?type=1',
    })
  }
})